const md5 = require("md5")

// 同步所有模型
const admin = require("./model/adminModel")
const banner = require("./model/bannerModel")
const blogType = require("./model/blogTypeModel")
const blog = require("./model/blogModel")
const demo = require("./model/demoModel")
const message = require("./model/messageModel")
const settingModel = require("./model/settingModel");
const about = require("./model/aboutModel")


// 数据库连接实例
const sequelize = require("./dbConnect");

(async function() {

    // 模型的关系
    // 博客和分类
    blogType.hasMany(blog, { foreignKey: "categoryId", targetKey: "id" })
    blog.belongsTo(blogType, { foreignKey: "categoryId", targetKey: "id", as: "category" })


    // 博客和博客评论之间存在关联关系
    blog.hasMany(message, { foreignKey: 'blogId', target: 'id' });
    message.belongsTo(blog, { foreignKey: 'blogId', target: 'id', as: "blog" });

    await sequelize.sync({ alter: true })

    // 初始化需要的表数据
    const adminCount = await admin.count()
    const bannerCount = await banner.count()

    if (!adminCount) {
        await admin.create({
            loginId: "admin",
            name: "管理员",
            loginPwd: md5("123456")
        })
        console.log("初始化管理员数据完成");
    }
    if (!bannerCount) {

        const banners = [{
            "midImg": "/static/images/1.jpg",
            "bigImg": "/static/images/1.jpg",
            "title": "哒哒哒",
            "description": "dadasdadad"
        }, {
            "midImg": "/static/images/2.jpg",
            "bigImg": "/static/images/2.jpg",
            "title": "嘿嘿嘿",
            "description": "123321"
        }, {
            "midImg": "/static/images/3.jpg",
            "bigImg": "/static/images/3.jpg",
            "title": "你好啊",
            "description": "当当当"
        }]
        await banner.bulkCreate(banners)

        console.log("初始化首页数据完成");
    }

    const aboutCount = await about.count(); // 首先进行查询看有没有数据
    if (!aboutCount) {
        // 如果没有数据就进行初始化
        await about.create({
            url: "http://static-c6c8ed10-585c-4167-8a85-469e7887d6d0.bspapp.com"
        });
        console.log("初始化关于我数据...");
    }


    // 全局设置数据初始化
    const settingCount = await settingModel.count(); // 首先进行查询看有没有数据
    if (!settingCount) {
        // 如果没有数据就进行初始化
        await settingModel.create({
            avatar: '/static/images/avatar.jpeg',
            siteTitle: '我的个人空间',
            github: '',
            qq: '3263023350',
            qqQrCode: '/static/images/zuotian9652.jpg',
            weixin: 'yh777bao',
            weixinQrCode: '/static/images/zuotian9652.jpg',
            mail: 'duyi@gmail.com',
            icp: '黑ICP备17001719号',
            githubName: 'DuYi-Edu',
            favicon: 'http://mdrs.yuanjin.tech/Fs4CDlC6mwe_WXLMIiXcmSJLHO4f',
        });
        console.log("初始化全局设置数据...");
    }
    console.log("数据完成")
})()